package com.flycent.hqhs.ui;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.tsz.afinal.FinalActivity;
import net.tsz.afinal.FinalDb;
import net.tsz.afinal.annotation.view.ViewInject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;


import com.flycent.hqhs.App;
import com.flycent.hqhs.R;
import com.flycent.hqhs.bean.MySearchHistory;
import com.flycent.hqhs.http.WebClient;
import com.flycent.hqhs.http.WebException;
import com.flycent.hqhs.ui.view.AbsViewHolderAdapter;
import com.flycent.hqhs.ui.view.DoubleButtonDialog;
import com.flycent.hqhs.ui.view.HorizontalListView;
import com.flycent.hqhs.ui.view.ListViewRun;
import com.flycent.hqhs.util.ComparatorByID;

/**
 * 搜索
 * @author fbl
 */
@SuppressLint("HandlerLeak") 
public class SearchActivity extends BaseActivity {
	@ViewInject(id = R.id.search_clear , click = "butClick")ImageView mClearImg; 
	@ViewInject(id = R.id.search_edit_right_img)ImageView mEditRightImg; 
	@ViewInject(id = R.id.search_head_left_but, click = "butClick") ImageButton mLeftImgBut;
	@ViewInject(id = R.id.clear_search_history_but, click = "butClick") Button mClearBut;
	@ViewInject(id = R.id.auto_listview) ListViewRun mAutoListView;
	@ViewInject(id = R.id.auto_edit) EditText mAutoEdit;
	@ViewInject(id = R.id.search_button ,click = "butClick") Button mSeachBut;
	@ViewInject(id = R.id.search_scroll) ScrollView mScrollView;
	@ViewInject(id = R.id.hotsearch) HorizontalListView mHorizontalListView;
	@ViewInject(id = R.id.hot_layout) LinearLayout mHotLayout;

	public static final String SEARCH_HISTORY = "search_history";

	private List<MySearchHistory> mSearchHistoryList;
	private List<MySearchHistory> mList = new ArrayList<MySearchHistory>();
	private MySearchHistoryAdapter mAdapter;
	private FinalDb db;
	private boolean isTextChange = false;
	private DoubleButtonDialog mDoubleButtonDialog;
	private List<MySearchHistory> mSearchDetail;
	private SearchHorizontalAdapter mhAdapter;
	private List<String>  aaList ;
	private boolean isCates = false;

	public static SearchActivity instance = null;
	
	private Handler mHandler = new MyHandler(this);
	@Override
	protected void onCreate(Bundle savedInstance) {
		super.onCreate(savedInstance);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_search);
		FinalActivity.initInjectedView(this);

		instance = this;

		db = ((App) getApplication()).finalDb;

		init();
		doRequestHotSearch();
	}



	private void init() {

		mhAdapter = new SearchHorizontalAdapter(this, R.layout.item_text_background);
		mHorizontalListView.setAdapter(mhAdapter);


		mAdapter = new MySearchHistoryAdapter(this, R.layout.item_search_list_history);
		mAutoListView.setAdapter(mAdapter);

		/*为了解决list和scroll的冲突*/
		mAutoListView.setParentScrollView(mScrollView);
		mAutoListView.setMaxHeight(20000); 
		//刷新下list
		refreshList();

		mAutoListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View view, int position,
					long arg3) {

				if(mAdapter.getData().get(position).isCate()){
					isCates = true;
					String  ssString = mAdapter.getData().get(position).getCate();
					mAutoEdit.setText(ssString);
				}else {
					isCates = false;
					String  ssString = mAdapter.getData().get(position).getKeyword();
					mAutoEdit.setText(ssString);
				}

				mSeachBut.performClick();//相当于点击该Buttton
			}
		});

		mAutoListView.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				if(!isTextChange){
					showdeletDialog(position);
				}

				return true;
			}

		});
		mHorizontalListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position,
					long id) {

				String mstr = mhAdapter.getData().get(position).toString();
				mAutoEdit.setText(mstr);
				mSeachBut.performClick();//相当于点击该Buttton
			}

		});

		mAutoEdit.setOnEditorActionListener(new OnEditorActionListener() {
			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				if(actionId ==EditorInfo.IME_ACTION_SEARCH){
					// 先隐藏键盘
					((InputMethodManager) mAutoEdit.getContext().getSystemService(Context.INPUT_METHOD_SERVICE))
					.hideSoftInputFromWindow(SearchActivity.this.getCurrentFocus()
							.getWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);
					addSearchHistory();
					return true;
				}
				return false;
			}
		});

		/*为Edit监听字数改变的状态 */
		mAutoEdit.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {

				mSearchHistoryList = db.findAll(MySearchHistory.class);
				if( !invalidateText(mAutoEdit)){
					mHotLayout.setVisibility(View.GONE);
					mClearImg.setVisibility(View.VISIBLE);
					mEditRightImg.setVisibility(View.GONE);
					mClearBut.setVisibility(View.GONE);

					refreshOnChangeList();


				}else{
					mHotLayout.setVisibility(View.VISIBLE);
					mClearImg.setVisibility(View.GONE);
					mEditRightImg.setVisibility(View.VISIBLE);
					mClearBut.setVisibility(View.VISIBLE);
					refreshList();

				}
			}


			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,int after) {}
			@Override
			public void afterTextChanged(Editable s) {}
		});
	}

	private void doRequestHotSearch() {

		new Thread(){
			public void run() {
				try {
					aaList = WebClient.getInstance(SearchActivity.this).getKeyWord();
					mHandler.sendEmptyMessage(1);
				} catch (WebException e) {
					e.printStackTrace();
				}
			};
		}.start();

	}


	public void butClick (View v){
		if( v == mSeachBut){
			addSearchHistory();
		}

		if( v == mLeftImgBut){
			finish();
		}

		if( v == mClearImg ){
			mAutoEdit.setText("");
		}

		if( v == mClearBut){
			clearSearchHistory();
		}

	}

	/* 清除所有的搜索项*/
	private void clearSearchHistory() {
		db.deleteAll(MySearchHistory.class);
		refreshList();
	}

	/* 增加到搜索历史中*/
	public void addSearchHistory(){
		if( invalidateText(mAutoEdit,R.string.title_search_edit_hint)){
			return;
		}
		mSearchHistoryList = db.findAll(MySearchHistory.class);

		if(mSearchHistoryList.size() != 0){
			for(int i = 0;i < mSearchHistoryList.size(); i++){
				if(mSearchHistoryList.get(i).getKeyword().equals(getText(mAutoEdit))){
					db.deleteById(MySearchHistory.class, mSearchHistoryList.get(i).getId());
				}
			}
		}
		//保存搜索数据
		db.save(new MySearchHistory(getText(mAutoEdit)));

		Intent intent = new Intent(SearchActivity.this,SearchListActivity.class);

		if(isCates){
			intent.putExtra("CATEGORY_NAME", getText(mAutoEdit));
		}else {
			intent.putExtra("searchStr", getText(mAutoEdit));
		}
		intent.putExtra("from", "SearchActivity");
		startActivity(intent);
		isCates = false;
		//		refreshList();
	}


	/** listView 适配器*/
	public class MySearchHistoryAdapter extends AbsViewHolderAdapter<MySearchHistory>{

		public MySearchHistoryAdapter(Context context, int layoutRes) {
			super(context, layoutRes);
		}

		@Override
		protected void bindData(int pos, MySearchHistory itemData) {
			TextView textView = getViewFromHolder(R.id.auto_content);
			TextView textView1 = getViewFromHolder(R.id.auto_add);
			if( !itemData.isCate()){
				SpannableString s = new SpannableString(itemData.getKeyword());
				Pattern p = Pattern.compile(getText(mAutoEdit));
				Matcher m = p.matcher(s);
				while (m.find()) {
					int start = m.start();
					int end = m.end();
					s.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.search_text_bg)), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
				}
				textView.setText(s);

				if(itemData.getAmount() == null || "".equals(itemData.getAmount()) ){
					textView1.setText("");
				}else {
					textView1.setText("共"+itemData.getAmount()+"条结果");
				}

			}else {
				SpannableString s = new SpannableString("在"+itemData.getCate()+"分类中搜索");
				Pattern p = Pattern.compile(itemData.getCate());
				Matcher m = p.matcher(s);
				while (m.find()) {
					int start = m.start();
					int end = m.end();
					s.setSpan(new ForegroundColorSpan(Color.RED), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
				}
				textView.setText(s);
				textView1.setText("共"+itemData.getcAmount()+"条结果");
			}


		}

	}
	public class SearchHorizontalAdapter extends AbsViewHolderAdapter<String>{

		public SearchHorizontalAdapter(Context context, int layoutRes) {
			super(context, layoutRes);
		}

		@Override
		protected void bindData(int pos, String itemData) {
			Button mtext = getViewFromHolder(R.id.search_item_text);
			mtext.setText(itemData);

		}

	}

	/**
	 * 更新list
	 */
	@SuppressWarnings("unchecked")
	private void refreshList(){
		mSearchHistoryList = db.findAll(MySearchHistory.class);
		if(mSearchHistoryList.size() > 0 ){
			mClearBut.setVisibility(View.VISIBLE);
		}else {
			mClearBut.setVisibility(View.GONE);
		}

		ComparatorByID comparator = new ComparatorByID();
		Collections.sort(mSearchHistoryList, comparator);
		mAdapter.update(mSearchHistoryList);
		isTextChange = false;

	}
	/**
	 * 在OntextChange下匹配类似的搜索项
	 */
	private void refreshOnChangeList() {
		mList.clear();
		mAdapter.update(mList);
		//本地搜索历史的匹配，
		//		for(int i = 0; i< mSearchHistoryList.size();i++){
		//			if(mSearchHistoryList.get(i).getName().indexOf(getText(mAutoEdit)) != -1){
		//				mList.add(new MySearchHistory(mSearchHistoryList.get(i).getId(),mSearchHistoryList.get(i).getName()));
		//			}
		//		}
		//		mAdapter.update(mList);//本地保存的搜索历史

		//		showLoadingDialog("");
		new Thread(){
			public void run() { 
				try {
					mSearchDetail =  WebClient.getInstance(SearchActivity.this).suggests(getText(mAutoEdit));

					for(int i = 0;i < mSearchDetail.size();i++ ){
						mList.add(new MySearchHistory(mSearchDetail.get(i).getKeyword(),mSearchDetail.get(i).getAmount()));
						if( i == 0 &&  mSearchDetail.get(i).getCate() != null ){
							mList.add(new MySearchHistory(mSearchDetail.get(i).getCate(),mSearchDetail.get(i).getcAmount(),true));
						}
					}

					mHandler.sendEmptyMessage(0);
				} catch (Exception e) {
				}
			};

		}.start();
		isTextChange = true;
	}

	private void showdeletDialog(final int pos){
		dismissDeleteDialog();
		mDoubleButtonDialog = new DoubleButtonDialog(this);
		mDoubleButtonDialog.showDialog(getString(R.string.info_delet_this_search), new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				db.deleteById(MySearchHistory.class, mSearchHistoryList.get(pos).getId());
				refreshList();
			}
		});



	}
	
	private class MyHandler extends Handler{
		private WeakReference<Activity> mActivity;
		
		private MyHandler(Activity activity){
			mActivity = new WeakReference<Activity>(activity);
		}
		
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if(mActivity.get() != null ){
				switch (msg.what) {
				case 0:
					//				dismissLoadingDialog();
					mAdapter.update(mList);//网络请求后的相关
					break;

				case 1:
					mhAdapter.update(aaList);
					break;

				default:
					break;
				}
			}
		}
	}


	private void dismissDeleteDialog() {

		if( mDoubleButtonDialog != null && mDoubleButtonDialog.isShowing() ) {
			mDoubleButtonDialog.dismiss();
		}
		mDoubleButtonDialog = null;

	}
	@Override
	protected void onResume() {
		super.onResume();
		mAutoEdit.setText("");
		mAutoEdit.clearFocus();
	}


	@Override
	protected void onDestroy() {
		dismissDeleteDialog();
		mHandler.removeCallbacksAndMessages(null);
		super.onDestroy();
	}


}
